<route lang="json5">
{
  needLogin: true,
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '任务详情',
  },
}
</route>

<template>
  <view class="min-h-screen bg-[#F5F5F5]">
    <wd-navbar
      :title="taskInfo.title"
      left-arrow
      @click-left="handleBack"
      custom-class="bg-white"
    ></wd-navbar>

    <!-- 内容区域 -->
    <view class="content-wrap px-[32rpx] pt-[24rpx] pb-[120rpx]">
      <!-- 任务基本信息卡片 -->
      <view class="bg-white rounded-lg p-[24rpx] mb-[24rpx]">
        <view class="flex justify-between items-center mb-[16rpx]">
          <view class="text-[30rpx] color-#333 font-bold">任务名称</view>
          <view class="text-[30rpx] color-#333">{{ taskInfo.title }}</view>
        </view>
        <view class="flex justify-between items-center mb-[16rpx]">
          <view class="text-[30rpx] color-#333 font-bold">截止完成时间</view>
          <view class="text-[30rpx] color-#333">{{ taskInfo.endTime }}</view>
        </view>
        <view class="mb-[16rpx]">
          <view class="text-[30rpx] color-#333 font-bold mb-[16rpx]">任务描述</view>
          <view class="text-[26rpx] color-#666 leading-[36rpx]">{{ taskInfo.description }}</view>
        </view>
        <view>
          <view class="flex items-center mb-[16rpx]">
            <view class="w-[4rpx] h-[28rpx] bg-[#3670F7] mr-[12rpx]"></view>
            <view class="text-[30rpx] color-#333 font-bold">附件</view>
          </view>
          <view
            class="grid grid-cols-3 gap-[16rpx]"
            v-if="taskInfo.attachments && taskInfo.attachments.length > 0"
          >
            <view
              v-for="(file, index) in taskInfo.attachments"
              :key="index"
              class="flex flex-col items-center bg-[#f3f5f7] rounded-lg p-[16rpx]"
              @click="previewFile(file)"
            >
              <image :src="getFileIcon(file.type)" class="w-[40rpx] h-[40rpx] mb-[8rpx]" />
              <view class="text-[24rpx] color-#333 text-center truncate w-full">
                {{ file.name }}
              </view>
              <view class="text-[20rpx] color-#999 mt-[4rpx]">{{ formatFileSize(file.size) }}</view>
            </view>
          </view>
          <view v-else class="text-[26rpx] color-#999 text-center py-[32rpx]">暂无附件</view>
        </view>
      </view>

      <!-- 作业回答区域 -->
      <view class="bg-white rounded-lg p-[24rpx] mb-[24rpx]">
        <view class="flex items-center mb-[24rpx]">
          <view class="w-[4rpx] h-[28rpx] bg-[#3670F7] mr-[12rpx]"></view>
          <view class="text-[30rpx] color-#333 font-bold">作业回答</view>
        </view>
        <view v-if="taskInfo.submitted">
          <!-- 已提交状态 -->
          <view class="bg-[#f5f5f5] p-[24rpx] rounded-lg">
            <view class="text-[28rpx] color-#666 mb-[24rpx] leading-[40rpx]">
              {{ taskInfo.submitContent }}
            </view>
            <!-- 已提交文件列表 -->
            <view
              v-for="(file, index) in taskInfo.submitFiles"
              :key="index"
              class="flex items-center bg-white rounded-lg mb-[16rpx] px-[24rpx] h-[120rpx]"
              @click="previewFile(file)"
            >
              <image :src="getFileIcon(file.type)" class="w-[48rpx] h-[48rpx]" />
              <view class="flex-1 ml-[16rpx]">
                <view class="text-[28rpx] color-#333">{{ file.name }}</view>
                <view class="text-[24rpx] color-#999 mt-[8rpx]">
                  {{ formatFileSize(file.size) }}
                </view>
              </view>
            </view>
            <view class="text-[24rpx] color-#999 text-right mt-[16rpx]">
              提交时间：{{ taskInfo.submitTime }}
            </view>
          </view>
        </view>
        <view v-else>
          <!-- 未提交状态 -->
          <view class="mb-[24rpx]">
            <wd-textarea
              v-model="submitForm.content"
              placeholder="请输入作业内容"
              class="textarea-wrap"
              :maxlength="500"
              show-word-limit
            />
          </view>

          <!-- 文件上传区域 -->
          <view class="mb-[32rpx]">
            <view class="flex flex-col mb-[16rpx]">
              <text class="text-[28rpx] color-#333 mb-[8rpx]">上传文件</text>
              <text class="text-[24rpx] color-#999">
                支持rar/zip/docx/pdf/jpg...格式，单个文件不超过10M
              </text>
            </view>

            <!-- 上传按钮 -->
            <view class="bg-[#f5f5f5] rounded-lg px-[24rpx] h-[88rpx] flex items-center">
              <view class="flex items-center" @click="chooseFile">
                <wd-icon name="add" size="36rpx" color="#3670F7" />
                <text class="text-[26rpx] color-#3670F7 ml-[8rpx]">上传文件</text>
              </view>
            </view>

            <!-- 已上传文件列表 -->
            <view
              v-for="(file, index) in submitForm.files"
              :key="index"
              class="flex items-center bg-[#f5f5f5] rounded-lg mt-[16rpx] px-[24rpx] h-[88rpx]"
            >
              <image :src="getFileIcon(file.type)" class="w-[40rpx] h-[40rpx]" />
              <view class="flex-1 ml-[16rpx]">
                <view class="text-[26rpx] color-#333 truncate">{{ file.name }}</view>
                <view class="text-[22rpx] color-#999 mt-[4rpx]">
                  {{ formatFileSize(file.size) }}
                </view>
              </view>
              <wd-icon name="close" size="36rpx" color="#999" @click="removeFile(index)" />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view v-if="!taskInfo.submitted" class="fixed-bottom bg-white">
      <view class="px-[32rpx] py-[16rpx]">
        <wd-button
          type="primary"
          block
          class="h-[88rpx] rounded-full"
          :loading="submitting"
          @click="handleSubmit"
        >
          提交
        </wd-button>
      </view>
    </view>

    <!-- 文件预览弹窗 -->
    <wd-popup v-model="showPreview" position="bottom" :style="{ height: '80vh' }">
      <view class="preview-header flex items-center justify-between px-[32rpx] py-[24rpx]">
        <view class="text-[30rpx] color-#333 font-bold truncate flex-1">
          {{ currentFile?.name }}
        </view>
        <wd-icon name="close" size="36rpx" @click="closePreview" />
      </view>
      <view class="preview-content" style="height: calc(80vh - 88rpx)">
        <file-preview
          v-if="showPreview"
          :file-url="currentFile?.url"
          :file-name="currentFile?.name"
        />
      </view>
    </wd-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useUserStore } from '@/store'
import FilePreview from '@/components/file-preview/file-preview.vue'

const userStore = useUserStore()

// 任务信息
const taskInfo = ref({
  id: '',
  title: '芭蕾舞基础练习作业',
  description:
    '芭蕾舞基础认识作业练习应聚焦于基本姿势，手位脚位以及如何身体协调性培养。通过反复练习Barre（把杆）上的Tendu（伸展脚）、Plié（蹲）等动作，理解身体线条的延伸与力量的平衡，逐步建立芭蕾舞者所需的优雅体态���基础技巧。',
  endTime: '2024-12-10',
  status: '进行中',
  attachments: [
    {
      name: '芭蕾管理基础功能.word',
      type: 'word',
      size: 1024 * 1024 * 2,
      url: 'https://example.com/file.docx',
    },
    {
      name: '课件.PPT',
      type: 'ppt',
      size: 1024 * 1024 * 3,
      url: 'https://example.com/file.ppt',
    },
  ],
  submitted: false,
  submitContent: '',
  submitFiles: [],
  submitTime: '',
})

// 状态样式
const statusClass = computed(() => {
  const status = taskInfo.value.status
  if (status === '进行中') return 'color-#3670F7'
  if (status === '已完成') return 'color-#3670F7'
  return 'color-#ff3b30'
})

// 提交表单
const submitForm = ref({
  content: '',
  files: [],
})

// 上传配置
const uploadAction = import.meta.env.VITE_APP_BASE_URL + '/upload'
const uploadHeaders = {
  Authorization: 'Bearer ' + userStore.token,
}

// 文件处理
const getFileIcon = (type: string) => {
  // 根据文件类型返回对应图标
  return `/static/images/file/${type}.png`
}

const formatFileSize = (size: number) => {
  if (size < 1024) return size + 'B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(2) + 'KB'
  return (size / 1024 / 1024).toFixed(2) + 'MB'
}

// 文件预览相关
const showPreview = ref(false)
const currentFile = ref<any>(null)

// 预览文件
const previewFile = (file: any) => {
  currentFile.value = file
  showPreview.value = true
}

// 关闭预览
const closePreview = () => {
  showPreview.value = false
  currentFile.value = null
}

// 上传回调
const handleUploadSuccess = (res: any, file: any) => {
  console.log('上传成功', res, file)
}

const handleUploadError = (err: any, file: any) => {
  console.error('上传失败', err)
  uni.showToast({
    title: '文件上传失败',
    icon: 'none',
  })
}

// 提交作业
const submitting = ref(false)
const handleSubmit = async () => {
  if (!submitForm.value.content && submitForm.value.files.length === 0) {
    uni.showToast({
      title: '请输入作业内容或上传文件',
      icon: 'none',
    })
    return
  }

  submitting.value = true
  try {
    // TODO: 调用提交作业接口
    // await submitTask({
    //   taskId: taskInfo.value.id,
    //   content: submitForm.value.content,
    //   files: submitForm.value.files
    // })

    uni.showToast({
      title: '提交成功',
      icon: 'success',
    })

    // 更新面状态
    taskInfo.value.submitted = true
    taskInfo.value.submitContent = submitForm.value.content
    taskInfo.value.submitFiles = submitForm.value.files
    taskInfo.value.submitTime = new Date().toLocaleString()
    taskInfo.value.status = '已完成'
  } catch (error) {
    console.error('提交失败', error)
    uni.showToast({
      title: '提交失败',
      icon: 'error',
    })
  } finally {
    submitting.value = false
  }
}

// 返回上一页
const handleBack = () => {
  uni.navigateBack()
}

// 页面加载
onLoad((options: any) => {
  const id = options.id
  // TODO: 根据id获取任务详情
  console.log('任务ID:', id)
})

// 选择文件
const chooseFile = () => {
  uni.chooseFile({
    count: 5 - submitForm.value.files.length,
    extension: ['.doc', '.docx', '.pdf', '.jpg', '.png'],
    success: (res) => {
      const files = res.tempFiles.map((file) => ({
        name: file.name,
        url: file.path,
        size: file.size,
        type: file.name.split('.').pop(),
      }))
      submitForm.value.files.push(...files)
    },
  })
}

// 移除文件
const removeFile = (index: number) => {
  submitForm.value.files.splice(index, 1)
}
</script>

<style lang="scss" scoped>
.content-wrap {
  min-height: calc(100vh - 88rpx);
}

.fixed-bottom {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100;
  padding-bottom: env(safe-area-inset-bottom);
}

.textarea-wrap {
  :deep(.wd-textarea) {
    width: 100%;
    min-height: 240rpx;

    .wd-textarea__inner {
      padding: 24rpx;
      font-size: 28rpx;
      line-height: 1.5;
      color: #333;
      background-color: #f3f5f7;
      border-radius: 8rpx;

      &::placeholder {
        font-size: 28rpx;
        color: #999999;
      }
    }

    .wd-textarea__word-limit {
      padding-top: 8rpx;
      font-size: 24rpx;
      color: #999999;
      text-align: right;
    }
  }
}

:deep(.wd-button--primary) {
  background: linear-gradient(to right, #7bffe6, #19d18b);
  border: none;

  &.is-disabled {
    background: #b3f0d9;
    opacity: 1;
  }
}

:deep(.wd-navbar) {
  .wd-navbar__title {
    font-size: 34rpx;
    font-weight: 500;
    color: #333;
  }
}

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
}

.grid > view {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  aspect-ratio: 1;
  padding: 16rpx;
  cursor: pointer;
  background-color: #f3f5f7;
  border-radius: 8rpx;
  transition: all 0.3s;

  &:active {
    opacity: 0.8;
  }

  .truncate {
    width: 100%;
    overflow: hidden;
    text-align: center;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
